package javaSerialize

import (
	"duanju-mq/pkg/javaSerialize/javaSerializeJavaIO"
	"encoding/base64"
	"encoding/json"
	"strings"
)

type javaSerializeData struct {
	Data *javaSerializeJavaIO.JavaTcObject
}

func ParseJavaSerialize(data string) (*javaSerializeData, error) {
	content, err := Base64DecodeString(data)
	if err != nil {
		return nil, err
	}
	buf := strings.NewReader(string(content))
	arr := make([]byte, 1<<7) // 128
	if _, err = buf.Read(arr[:4]); err != nil {
		return nil, err
	}
	refs := make([]*javaSerializeJavaIO.JavaReferenceObject, 1<<7)
	jo := &javaSerializeJavaIO.JavaTcObject{}
	if err = jo.Deserialize(buf, refs); err != nil {
		return nil, err
	}
	return &javaSerializeData{Data: jo}, nil
}
func (t *javaSerializeData) Unmarshal(v any) error {
	dd, err := json.Marshal(t.Data.JsonMap())
	if err != nil {
		return err
	}
	err = json.Unmarshal(dd, v)
	return err
}
func (t *javaSerializeData) ReplaceClassNameString(className string) (string, error) {
	t.Data.Classes[0].ClassName = className
	var buf = new(strings.Builder)
	if err := javaSerializeJavaIO.SerializeJavaEntity(buf, t.Data); err != nil {
		return "", err
	} else {
		return base64.URLEncoding.EncodeToString([]byte(buf.String())), nil
	}
}

func Base64DecodeString(data string) ([]byte, error) {
	content, err := base64.URLEncoding.DecodeString(data)
	if err != nil {
		content, err = base64.RawURLEncoding.DecodeString(data)
	}
	return content, err
}
